package com.demo.crm.springboot3security.security;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * JWT认证过滤器
 * 负责处理JWT token的验证和用户认证
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JwtTokenUtil jwtTokenUtil;
    private final CustomUserDetailsService userDetailsService;
    // 用于路径匹配的工具类
    private final AntPathMatcher pathMatcher = new AntPathMatcher();

    // 不需要进行JWT验证的路径
    private final List<String> excludedPaths = Arrays.asList(
            "/api/auth/login",
            "/api/auth/register",
            "/test",
            "/error",
            "/actuator/caches",
            "/actuator/prometheus",
            "/actuator/metrics/cache.size",
            "/actuator/metrics/cache.gets",
            "/actuator/metrics/cache.evictions",
            "/metrics");

    /**
     * 判断请求是否需要进行JWT验证
     * 
     * @param request HTTP请求
     * @return true表示不需要验证，false表示需要验证
     */
    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        boolean shouldNotFilter = excludedPaths.stream()
                .anyMatch(pattern -> pathMatcher.match(pattern, path));
        log.debug("Path: {}, shouldNotFilter: {}", path, shouldNotFilter);
        return shouldNotFilter;
    }

    /**
     * 处理JWT认证的主要逻辑
     * 
     * @param request  HTTP请求
     * @param response HTTP响应
     * @param chain    过滤器链
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        try {
            String jwt = parseJwt(request);
            log.debug("Processing request: {} {}, JWT: {}", request.getMethod(), request.getRequestURI(),
                    jwt != null ? "present" : "not present");

            if (jwt != null) {
                String username = jwtTokenUtil.getUsernameFromToken(jwt);
                log.debug("JWT username: {}", username);

                if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                    UserDetails userDetails = userDetailsService.loadUserByUsername(username);
                    log.debug("Loaded UserDetails: {}", userDetails.getUsername());

                    if (jwtTokenUtil.validateToken(jwt)) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                userDetails,
                                null,
                                userDetails.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        log.debug("Set authentication in SecurityContext, authorities: {}",
                                userDetails.getAuthorities());
                    } else {
                        log.warn("JWT token validation failed");
                    }
                }
            } else {
                log.debug("No JWT token found in request");
            }
        } catch (Exception e) {
            log.error("Cannot set user authentication", e);
        }

        chain.doFilter(request, response);
    }

    private String parseJwt(HttpServletRequest request) {
        String headerAuth = request.getHeader("Authorization");
        log.debug("Authorization header: {}", headerAuth);

        if (StringUtils.hasText(headerAuth) && headerAuth.startsWith("Bearer ")) {
            return headerAuth.substring(7);
        }

        return null;
    }
}